package bank;

import java.util.Random;

public class Main {

	static final int ACC_COUNT = 1000;
	static final int MAX_SUM= 1000;
	static final int THREADS_COUNT = 300;
	static final int TRANSFER_COUNT = 10000;
	static final int MAX_TRANSFER_SUM = 500;
	
	public static void main(String[] args) {
		testBank();
	}
	
	public static void testBank() {
		//Create bank and add accounts
		final Bank bank = new Bank();
		Random rnd = new Random();
		for (int i=0; i<ACC_COUNT; i++) {
			Account acc = new Account(i,rnd.nextInt(MAX_SUM));
			bank.addAccount(acc);
		}
		//Save initial sum
		int sumBeforeTesting = bank.getAllMoney();
		System.out.println("Before testing: "+sumBeforeTesting+"$");
		
		//Execute transfers in many threads
		Thread[] threads = new Thread[THREADS_COUNT];
		for (int i=0; i<THREADS_COUNT; i++) {
			threads[i] = new Thread(new Runnable() {

				@Override
				public void run() {
					Random innerRnd = new Random();
					int nfrom;
					int nto;
					int amount;
					for (int j=1; j<TRANSFER_COUNT; j++) {
						nfrom = innerRnd.nextInt(ACC_COUNT);
						do {
						     nto = innerRnd.nextInt(ACC_COUNT);
						} while (nfrom==nto); 
						amount = innerRnd.nextInt(MAX_TRANSFER_SUM);
						bank.transferByIndexes(nfrom, nto, amount);
					}
				}
				
			});
			threads[i].start();
		}
		
		//Waiting for end of transactions
		for (Thread t : threads) {
			try {
				t.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		int sumAfterTesting = bank.getAllMoney();
		System.out.println("Sum after testing: "+sumAfterTesting+"$");
		System.out.println("Bank works "+((sumAfterTesting==sumBeforeTesting)?"correctly":"wrong"));
		
	}

}
